// import uni, { getCurrentPages, navigateTo } from "@unijs/uni";
import config from "./config";
import httpRequest from "./http.request";
import dayjs from "dayjs";
import {
	createActivityBrowse,
	updateActivityBrowse,
	createStaffFission,
	createCustomerFission,
	getCustomerByOpenId,
	mergeGuestToCustomer,
	createCustomerLoginRelationship
} from "./api";

export const pageBrowseStart = async (store, pageName, activityInfo, activityItemInfo) => {
	let pages = getCurrentPages(); //获取页面信息栈
	let currentPage = pages[pages.length - 1]; //获取当前访问页面信息

	let data = {
		route: currentPage.route,
		gbPage: pageName,
		gbInti: new Date().getUTCTime(), //进入时间
		options: currentPage.options,
	};
	if (activityItemInfo?.giUuid) {
		data.giUuid = activityItemInfo.giUuid;
		data.giName = activityItemInfo.giName;
	}

	if (activityInfo) {
		data.gpUuid = activityInfo.gpUuid;
	}

	let userInfo = uni.getStorageSync("userInfo") || {};

	if (userInfo?.ciUuid) data.ciUuid = userInfo.ciUuid;
	if (userInfo?.ciName) data.ciName = userInfo.ciName;
	if (userInfo?.nickName) data.ciAlia = userInfo.nickName;

	if (userInfo?.isNew) {
		data.ciType = userInfo.isNew === true ? "新客" : "老客";
	}

	let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
	let staffId = uni.getStorageSync("staffId") || ""; // 员工ID

	if (staffId) data.gbSsid = staffId;
	if (shareId) data.gbScid = shareId;
	let res = await createActivityBrowse(data);
	if (res) {
		data.gbUuid = res.gbUuid;
		let userInfo = uni.getStorageSync("userInfo") || {};
		let uInfo = {
			...userInfo,
			nickName: res.ciAlia,
			ciUuid: res.ciUuid,
		};
		store.dispatch("personInfo/save", {
			userInfo: uInfo,
		});
		return {
			...uInfo,
			gbUuid: data.gbUuid,
			gbInti: data.gbInti,
		};
	}
	return {};
};

export const pageBrowseEnd = async (gbUuid, gbInti) => {
	let data = {
		gbUuid,
		gbInti,
	};
	data.gbOuti = new Date().getUTCTime(); //离开时间
	data.gbTime = Number(data.gbOuti) - Number(data.gbInti); //浏览时长
	if (data.gbUuid) {
		await updateActivityBrowse(data);
	}
};

export const userAuthorization = async (gpUuid) => {
	let res = await uni.getUserProfile({
		desc: "用于完善用户资料",
	});
	if (res.errMsg === "getUserProfile:ok") {
		const loginRes = await uni.login({});
		let userInfo = uni.getStorageSync("userInfo"); // 游客信息
		let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
		let staffId = uni.getStorageSync("staffId") || ""; // 员工ID
		
		if (loginRes.code) {
			// 缓存userInfo
			let brwseData = {
				ciUuid: userInfo.ciUuid
			};

			const keys = await httpRequest({
				url: "/merchants/weixin/miniapp/code2Session",
				data: {
					appid: config.appid,
					organizationUuid: config.organizationUuid,
					js_code: loginRes.code,
					grant_type: "authorization_code",
				},
				object: "organization",
			});
			if (keys) {
				res.userInfo.session_key = keys.session_key;
				res.userInfo.openId = keys.openid;

				let resCust = await getCustomerByOpenId(keys.openid);

				if (resCust?.ciPhon) {
					res.userInfo.ciUuid = resCust?.ciUuid;
					res.userInfo.phone = resCust?.ciPhon;
					res.userInfo.isNew = resCust?.ciFrom === "新客" ? true : false;
					res.userInfo.ciName = resCust?.ciName;
					res.userInfo.isLogin = true;

					brwseData.ciUuidNew = resCust?.ciUuid;;
					brwseData.ciAlia = res.userInfo.nickName;
					brwseData.ciType = resCust?.ciFrom === "新客" ? "新客" : "老客"
					
					//创建客户关系
					let rlData = {
					    gpUuid: gpUuid,
					    ciUuid: resCust?.ciUuid,
					    clTime: new Date().getUTCTime(),
					};
					if (shareId) rlData.scUuid = shareId;
					if (staffId) rlData.orUuid = staffId;
					if ((staffId || shareId) && gpUuid) {
					    createCustomerLoginRelationship(rlData);
					}

					//合并游客信息到客户
					mergeGuestToCustomer(brwseData);
				}
			}
		}

		return {
			...userInfo,
			...res.userInfo,
		};
	} else return null;
};

export const isValidPhone = (phone) => {
	let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
	if (!myreg.test(phone)) {
		return false;
	} else {
		return true;
	}
};

export const numberFormat = (number, decimals = 2, decPoint = ".", thousandsSep = ",", roundtag) => {
	/*
	 * 参数说明：
	 * number：要格式化的数字
	 * decimals：保留几位小数
	 * dec_point：小数点符号
	 * thousands_sep：千分位符号
	 * roundtag:舍入参数，默认 'ceil' 向上取,'floor'向下取,'round' 四舍五入
	 * */
	number = (number + "").replace(/[^0-9+-Ee.]/g, "");
	roundtag = roundtag || "ceil"; // 'ceil','floor','round'
	let n = !isFinite(+number) ? 0 : +number;
	var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
	var sep = typeof thousandsSep === "undefined" ? "," : thousandsSep;
	var dec = typeof decPoint === "undefined" ? "." : decPoint;
	var s = "";
	var toFixedFix = function (n, prec) {
		var k = Math.pow(10, prec);
		return "" + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k;
	};
	s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
	var re = /(-?\d+)(\d{3})/;
	while (re.test(s[0])) {
		s[0] = s[0].replace(re, "$1" + sep + "$2");
	}
	if ((s[1] || "").length < prec) {
		s[1] = s[1] || "";
		s[1] += new Array(prec - s[1].length + 1).join("0");
	}
	return s.join(dec);
};

export const UTCTimeToLocal = (time, format = "YYYY-MM-DD HH:mm:ss") => {
	if (!time) return "";
	let localTime = time - new Date().getTimezoneOffset() * 60 * 1000;
	if (format) return dayjs(localTime).format(format);
	return localTime;
};

export const getCountDown = (time) => {
	return parseInt((Number(time) - Number(new Date().getUTCTime())) / 1000);
};

export const getNumIndex = (price) => {
	price = price + "";
	let numGp = price.length - 4;
	let numIndex = "";
	for (let i = 0; i < numGp; i++) {
		numIndex += "?";
	}
	return numIndex;
};

export const saveShareRecord = (gpUuid) => {
	// TODO: 记录分享来至按钮还是菜单，并保存分享记录
	let userInfo = uni.getStorageSync("userInfo") || "";
	let staffId = uni.getStorageSync("staffId") || ""; // 员工Id
	let staffInfo = uni.getStorageSync("staffInfo") || null; // 员工
	let shUuid = uni.getStorageSync("shareId") || "";

	if (staffInfo?.orUuid) {
		shUuid = ""
		createStaffFission({
			orUuid: staffInfo.orUuid,
			gpUuid: gpUuid || "",
			orName: staffInfo.orName,
			sfShat: 1,
		});
	} else {
		if (userInfo?.openId && userInfo?.isLogin === true) {
			shUuid = userInfo.ciUuid
			createCustomerFission({
				ciUuid: userInfo.ciUuid,
				gpUuid: gpUuid || "",
				cfAvat: userInfo?.avatarUrl,
				cfShat: 1,
				cfWcna: userInfo.nickName,
				ciName: userInfo.ciName,
				ciType: userInfo.isNew ? "新客" : "老客",
			});
		}
	}

	return {
		staffId,
		shUuid,
	};
};

export const getNo = (index) => {
	if (index === 0) return "error";
	if (index === 1) return "primary";
	if (index === 2) return "success";
	if (index === 3) return "warning";
	return "default";
};
